<template>
  <xr-create
    :loading="loading"
    :title="title"
    :confirm-button-text="confirmButtonText"
    :show-confirm="config.showConfirm"
    :show-cancel="config.showCancel"
    @close="close"
    @save="saveClick">
    <i
      slot="title-append"
      class="wk wwk-icon-fill-help wk-help-tips"
      data-type="13"
      data-id="40" />
    <create-sections
      :title="$t('crm.invoice.b5363a04b0036f80ca349dc41f837c64')">
      <el-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :validate-on-rule-change="false"
        class="wk-form"
        label-position="top">
        <wk-form-items
          v-for="(children, childIndex) in fieldList"
          :key="childIndex"
          :field-from="fieldForm"
          :field-list="children"
          :ignore-fields="ignoreFields"
          @change="formChange">
          <template slot-scope="{ data, index }">
            <el-select
              v-if="data && data.field == 'invoiceType'"
              v-model="fieldForm[data.field]"
              :disabled="data.disabled"
              :placeholder="data.disabled ? '' : undefined"
              style="width: 100%;"
              @change="formChange(data, index, $event)">
              <el-option
                v-for="(item, sindex) in data.setting || []"
                :key="sindex"
                :label="item"
                :value="item" />
            </el-select>
            <el-select
              v-else-if="data && data.field == 'titleType'"
              v-model="fieldForm[data.field]"
              :disabled="data.disabled"
              :placeholder="data.disabled ? '' : undefined"
              style="width: 100%;"
              @change="formChange(data, index, $event)">
              <el-option
                v-for="item in titleTypeOptions"
                :key="item.value"
                :label="item.name"
                :value="item.value" />
            </el-select>
            <crm-relative-cell
              v-if="data && data.formType == 'customer'"
              :value="fieldForm[data.field]"
              :disabled="data.disabled"
              data-type="customer"
              @value-change="otherChange($event, data)"
            />
            <crm-relative-cell
              v-if="data && ['contract','receivables'].includes(data.formType)"
              :value="fieldForm[data.field]"
              :disabled="data.disabled"
              :props="data.props"
              :data-type="data.formType"
              @value-change="otherChange($event, data)"
            />
          </template>
        </wk-form-items>
      </el-form>
    </create-sections>

    <create-sections
      v-if="!config.getFields"
      :title="$t('crm.invoice.ea48247d9c3874c69428a54d9bfc6bb5')">
      <div style="padding: 0 12px; text-align: right;">
        <el-button
          :disabled="!(fieldForm.customerId && fieldForm.customerId.length > 0)"
          type="primary"
          @click="showSelectView=true">
          {{ $t('crm.invoice.bae2c744940c3a9da496075e3d4f0808') }}
        </el-button>
        <crm-relative
          v-if="showSelectView"
          ref="crmrelative"
          :visible.sync="showSelectView"
          :props="titleAction"
          data-type="invoiceTitle"
          radio
          @changeCheckout="titleSelectChange" />
      </div>
      <el-form
        ref="otherFrom"
        :model="otherFrom"
        :rules="otherRules"
        class="wk-form is-two-columns"
        label-position="top">
        <wk-form-item
          v-for="(item, index) in otherFields"
          v-show="!item.hidden"
          :key="item.key"
          :item="item"
          :index="index"
          :field-from="otherFrom"
          :disabled="item.disabled"
          @change="otherFieldValueChange" />
      </el-form>
    </create-sections>

    <create-sections
      v-if="!config.getFields"
      :title="$t('crm.invoice.29a85c8ac6502c4c34c21f05ba66a5f5')">
      <el-form
        ref="mailFrom"
        :model="mailFrom"
        :rules="mailRules"
        class="wk-form is-two-columns"
        label-position="top">
        <wk-form-item
          v-for="(item, index) in mailFields"
          :key="item.key"
          :item="item"
          :index="index"
          :field-from="mailFrom"
          :disabled="item.disabled" />
      </el-form>
    </create-sections>

    <!-- <create-sections
      v-if="wkFlowList"
      :title="$t('crm.invoice.cedfda21d5e27fe7b35deb908980813c')">
      <template slot="header">
        <el-tooltip
          v-if="flowRemarks"
          :content="flowRemarks"
          effect="dark"
          placement="top">
          <i class="wk wk-help wk-help-tips" style="margin-left: 8px;" />
        </el-tooltip>
      </template>
      <wk-approval-flow-apply
        :data="wkFlowList"
        :approver-edit-auth="approverEditAuth"
        :is-edit="examineInfo.hasOwnProperty('examineStatus') && examineInfo.examineStatus == 2"
        :carbon-copy-edit-auth="carbonCopyEditAuth"
        :examine-advanced-setting="examineAdvancedSetting"
        style="padding: 15px;"
      />
    </create-sections> -->
    <create-sections
      v-if="wkFlowList"
      title="审核信息">
      <template slot="header">
        <el-tooltip
          v-if="flowRemarks"
          :content="flowRemarks"
          effect="dark"
          placement="top">
          <i class="wk wk-help wk-help-tips" style="margin-left: 8px;" />
        </el-tooltip>
      </template>
      <wk-af-new-apply
        ref="afNewApply"
        :data="wkFlowList"
        :approver-edit-auth="approverEditAuth"
        :detail="examineAdvancedSetting"
        style="padding: 15px;" />
    </create-sections>
    <template slot="footer-left">
      <slot name="footer" />
    </template>
  </xr-create>
</template>

<script>
import { filedGetFieldAPI } from '@/api/crm/common'
import { crmInvoiceSaveAPI } from '@/api/crm/invoice'
import { crmCustomerInvoiceInfoAPI } from '@/api/crm/customer'

import XrCreate from '@/components/XrCreate'
import CreateSections from '@/components/CreateSections'
import WkFormItems from '@/components/NewCom/WkForm/WkFormItems'
import WkFormItem from '@/components/NewCom/WkForm/WkFormItem'
// import WkApprovalFlowApply from '@/components/Examine/WkApprovalFlowApply'
import WkApprovalFlowApplyMixin from '@/components/Examine/mixins/WkApprovalFlowApply'
import WkAfNewApply from '@/components/Examine/WkAfNewApply'
import {
  CrmRelativeCell
} from '@/components/CreateCom'

import crmTypeModel from '@/views/crm/model/crmTypeModel'
import tagProps from '@/views/crm/model/tagDefaultProps'
import CustomFieldsMixin from '@/mixins/CustomFields'
import CrmCreateMixin from '@/mixins/CrmCreateMixin'
import { objDeepCopy } from '@/utils'
import { isEmpty } from '@/utils/types'

export default {
  // 订单创建
  name: 'InvoiceCreate',
  components: {
    XrCreate,
    CreateSections,
    CrmRelativeCell,
    CrmRelative: () => import('@/components/CreateCom/CrmRelative'),
    // WkApprovalFlowApply,
    WkFormItems,
    WkFormItem,
    WkAfNewApply
  },
  mixins: [CustomFieldsMixin, WkApprovalFlowApplyMixin, CrmCreateMixin],
  props: {
    action: {
      type: Object,

      default() {
        return {
          type: 'save', // save relative 新建 相关新建   update 编辑
          id: '',
          data: {}
        }
      }
    },
    examineInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      titleFieldList: [
        { fieldName: 'titleType', formType: 'text', name: this.$t('crm.invoice.539aef1cf361e7a211da93b16cf8b275') },
        { fieldName: 'invoiceTitle', formType: 'text', name: this.$t('crm.invoice.f5ad7578ba3d12c2a0894d2486ee38c1') },
        { fieldName: 'taxNumber', formType: 'text', name: this.$t('crm.invoice.e05ab423e8777bf9e6902cbd7307b2dc') },
        { fieldName: 'depositBank', formType: 'text', name: this.$t('crm.invoice.e8baafdf8a0607fb6d42e230be22aba8') },
        { fieldName: 'depositAccount', formType: 'text', name: this.$t('crm.invoice.586238fc282669addae58e5689c473ad') },
        { fieldName: 'depositAddress', formType: 'text', name: this.$t('crm.invoice.df546e101165a73e2ca833b73b3c23d4') },
        { fieldName: 'telephone', formType: 'text', name: this.$t('crm.invoice.9a5fe387f776ca5e51d9218daeb5485b') }
      ],
      ignoreFields: [], // 之前是发票类型，目前忽略了
      baseFields: [],
      fieldList: [],
      fieldForm: {},
      fieldRules: {},
      showPopover: false,
      titleAction: {},
      showSelectView: false,
      // 发票信息
      otherFields: [],
      otherRules: {},
      otherFrom: {
        titleType: 1
      },

      // 邮寄信息
      mailFields: [],
      mailRules: {},
      mailFrom: {},
      // 审批信息
      flowRemarks: '',
      wkFlowList: null, // 有值有审批流
      approverEditAuth: false, // 固定审批人是否可修改
      carbonCopyEditAuth: false // 固定抄送人是否可修改
    }
  },
  computed: {
    editId() {
      return this.action.type == 'update' ? this.action.id : ''
    },

    title() {
      if (this.config.title) return this.config.title
      return this.isEdit ? this.$t('crm.invoice.486ab97dee005dc507f19f9c65cc5058') : this.$t('crm.invoice.36c3e2830d9fcd1df643e307b2eae688')
    },

    isEdit() {
      return !!this.editId
    },

    confirmButtonText() {
      if (this.wkFlowList) {
        return this.$t('crm.invoice.83a89afa0a3d482fe8ec09cded74ca22')
      }
      return this.$t('crm.invoice.f7c2ecc432f2068286643bbeab90f2b1')
    }
  },
  watch: {},
  created() {
    if (this.config.getFields) {
      this.getCustomField()
    } else {
      this.getField()
    }
  },
  mounted() {},

  beforeDestroy() {},
  methods: {
    /**
     * 获取数据
     */
    getField() {
      this.loading = true
      const params = {
        label: crmTypeModel.invoice
      }

      if (this.action.type == 'update') {
        params.id = this.action.id
      }

      filedGetFieldAPI(params)
        .then(res => {
          const list = res.data || []

          const baseFields = []
          const fieldList = []
          const fieldForm = {}

          list.forEach(children => {
            const fields = []
            children.forEach(item => {
              const temp = this.getFormItemDefaultProperty(item)
              temp.show = true

              if (this.ignoreFields.includes(temp.field)) {
                // 防止影响普通单选的验证方式
                delete temp.optionsData
                delete item.optionsData
              }

              const canEdit = this.getItemIsCanEdit(item, this.action.type)
              // 是否可编辑
              temp.disabled = !canEdit

              // 禁止某些业务组件选择
              if (['contract', 'customer', 'receivables'].includes(temp.formType)) {
                if (this.action.type === 'save') {
                  temp.disabled = ['contract', 'receivables'].includes(item.formType)
                } else if (this.action.type == 'relative') {
                  if (temp.formType == 'customer') {
                    // 客户下填充客户，禁止修改
                    const customerObj = this.action.data.customer
                    temp.disabled = !!customerObj
                  } else if (temp.formType == 'receivables') {
                    const receivablesObj = this.action.data.contract
                    temp.disabled = !receivablesObj
                  } else {
                    // 合同下填充合同，禁止修改客户和合同
                    const contractObj = this.action.data.contract
                    temp.disabled = !!contractObj
                  }
                }
              }

              if (temp.formType == 'field_tag') {
                temp['tagProps'] = tagProps({ params: { type: crmTypeModel.invoice }})
              }

              // 合同金额字段展示用
              if (temp.field === 'contractMoney') {
                temp.disabled = true
              }

              // 处理关联
              if (this.action.type == 'update' ||
              this.action.type == 'relative') {
                if (item.formType == 'contract') { // 合同 需要客户信息
                  const customerObj = this.getItemRelatveInfo(list, 'customer')
                  if (customerObj) {
                    temp.props = {
                      params: {
                        searchList: [
                          { formType: 'text', name: 'customer_id', type: 1, values: [customerObj.customerId] },
                          { formType: 'checkStatus', name: 'checkStatus', type: 1, values: [1, 10] }
                        ]
                      }
                    }

                    this.$set(this.mailFrom, 'contactsName', customerObj.contactsName)
                    this.$set(this.mailFrom, 'contactsMobile', customerObj.contactsMobile)
                    this.$set(this.mailFrom, 'contactsAddress', customerObj.contactsAddress)

                    this.titleAction = {
                      type: 'invoiceTitle',
                      name: this.$t('crm.invoice.d0cdc08b7b3b6dba982a7ff8d5ee95cd'),
                      isCommon: true, // 是统一效果
                      fieldList: this.titleFieldList,
                      request: crmCustomerInvoiceInfoAPI,
                      showHeader: false,
                      rowKey: 'infoId',
                      radio: true,
                      tableFormatter: this.titleTableFormatter,
                      params: {
                        customerId: customerObj.customerId
                      }
                    }
                  }
                } else if (item.formType == 'receivables') {
                  const contractObj = this.getItemRelatveInfo(list, 'contract')
                  if (contractObj) {
                    temp.props = {
                      params: {
                        searchList: [
                          { formType: 'text', name: 'contract_id', type: 1, values: [contractObj.contractId] }
                        ]
                      }
                    }
                  }

                  if (this.action.type == 'update') {
                    item.value ? item.value[0].number = item.value[0].receivablesNum : []
                  }
                  fieldForm.receivablesNum = item.value ? item.value[0].receivablesNum : ''
                }
              }

              // 特殊字段允许多选
              this.getItemRadio(item, temp)

              // 获取默认值
              if (temp.show) {
                if (this.ignoreFields.includes(temp.field)) {
                  fieldForm[temp.field] = this.isEdit ? temp.value : temp.defaultValue
                } else {
                  fieldForm[temp.field] = this.getItemValue(item, this.action.data, this.action.type)
                }
              }
              fields.push(temp)
              baseFields.push(item)
            })
            fieldList.push(fields)
          })

          // 处理相关新建金额值的填充
          if (this.action.type == 'relative') {
            const contractItem = this.getItemRelatveInfo(list, 'contract')
            // 关联新建填充金额
            if (contractItem) {
              fieldForm.contractMoney = contractItem ? contractItem.money : ''
              fieldForm.invoiceMoney = contractItem ? contractItem.money : ''
            }
          }

          this.baseFields = baseFields
          this.fieldList = fieldList

          const result = this.getFormContentByOptionsChange(fieldList, fieldForm)
          this.fieldForm = result.fieldForm
          this.fieldRules = result.fieldRules

          // 审核信息
          const examineParams = {
            label: 3
          }
          if (this.examineInfo.hasOwnProperty('examineStatus') && this.examineInfo.examineStatus == 2) {
            const { recordId } = this.examineInfo
            examineParams.recordId = recordId
          }

          this.initWkFlowData({
            params: examineParams,
            fieldForm: this.fieldForm
          }, res => {
            const list = res.list
            list.forEach(item => {
              if (item.rangeType === 2 || item.rangeType == 3) {
                item.finalUserList = objDeepCopy(item.userList)
                item.userList = []
              }
            })

            this.wkFlowList = res.list
            this.flowRemarks = res.resData ? res.resData.remarks : ''

            // 固定审批人/抄送人修改权限
            const modifyPermissionType = this.examineAdvancedSetting?.modifyPermissionType
            if (isEmpty(modifyPermissionType)) {
              this.approverEditAuth = true
              this.carbonCopyEditAuth = true
            } else {
              this.approverEditAuth = !modifyPermissionType.includes(1)
              this.carbonCopyEditAuth = !modifyPermissionType.includes(2)
            }
          })

          // 获取其他块字段
          this.getOtherField()
          // relative 下赋值联系人信息
          if (this.isEdit || this.action.type === 'relative') {
            const detail = this.action.detail

            const otherFrom = {}
            otherFrom.titleType = detail.titleType
            otherFrom.invoiceTitle = detail.invoiceTitle
            otherFrom.taxNumber = detail.taxNumber
            otherFrom.depositBank = detail.depositBank
            otherFrom.depositAccount = detail.depositAccount
            otherFrom.depositAddress = detail.depositAddress
            otherFrom.telephone = detail.telephone
            this.otherFrom = otherFrom

            const mailFrom = {}
            mailFrom.contactsName = detail.contactsName
            mailFrom.contactsMobile = detail.contactsMobile
            mailFrom.contactsAddress = detail.contactsAddress
            this.mailFrom = mailFrom
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * @description: 自定义获取
     * @return {*}
     */
    getCustomField() {
      this.loading = true
      this.config.getFields().then(fields => {
        console.log('fields---', fields)

        const list = this.convertToTwoFields(fields)
        const baseFields = []
        const fieldList = []
        const fieldForm = {}

        list.forEach(children => {
          const fields = []
          children.forEach(item => {
            const temp = this.getFormItemDefaultProperty(item)
            temp.show = true

            if (this.ignoreFields.includes(temp.field)) {
              // 防止影响普通单选的验证方式
              delete temp.optionsData
              delete item.optionsData
            }

            if (item.formType === 'serial_number') {
              temp.disabled = !(item.authLevel == 3) // 3是可编辑
              const setItem = temp.setting.find(obj => obj.type === 1)
              if (setItem) {
                // 优先读取字段里是否允许输入配置
                const allowedInput = setItem.allowedInput == 1
                if (allowedInput && temp.disabled) { // 如果禁止改为0
                  setItem.allowedInput = 0
                }
              }
            } else {
              const canEdit = this.getItemIsCanEdit(item, this.action.type)
              // 是否可编辑
              temp.disabled = !canEdit
            }

            // 禁止某些业务组件选择
            // if (['contract', 'customer', 'receivables'].includes(temp.formType)) {
            //   if (this.action.type === 'save') {
            //     temp.disabled = ['contract', 'receivables'].includes(item.formType)
            //   } else if (this.action.type == 'relative') {
            //     if (temp.formType == 'customer') {
            //       // 客户下填充客户，禁止修改
            //       const customerObj = this.action.data.customer
            //       temp.disabled = !!customerObj
            //     } else if (temp.formType == 'receivables') {
            //       const receivablesObj = this.action.data.contract
            //       temp.disabled = !receivablesObj
            //     } else {
            //       // 合同下填充合同，禁止修改客户和合同
            //       const contractObj = this.action.data.contract
            //       temp.disabled = !!contractObj
            //     }
            //   }
            // }

            if (temp.formType == 'field_tag') {
              temp['tagProps'] = tagProps({ params: { type: crmTypeModel.invoice }})
            }

            // 合同金额字段展示用
            if (temp.field === 'contractMoney') {
              temp.disabled = true
            }

            // 处理关联
            if (this.action.type == 'update' ||
              this.action.type == 'relative') {
              if (item.formType == 'contract') { // 合同 需要客户信息
                const customerObj = this.getItemRelatveInfo(list, 'customer')
                if (customerObj) {
                  temp.props = {
                    params: {
                      searchList: [
                        { formType: 'text', name: 'customer_id', type: 1, values: [customerObj.customerId] },
                        { formType: 'checkStatus', name: 'checkStatus', type: 1, values: [1, 10] }
                      ]
                    }
                  }

                  this.$set(this.mailFrom, 'contactsName', customerObj.contactsName)
                  this.$set(this.mailFrom, 'contactsMobile', customerObj.contactsMobile)
                  this.$set(this.mailFrom, 'contactsAddress', customerObj.contactsAddress)

                  this.titleAction = {
                    type: 'invoiceTitle',
                    name: '关联发票抬头',
                    isCommon: true, // 是统一效果
                    fieldList: this.titleFieldList,
                    request: crmCustomerInvoiceInfoAPI,
                    showHeader: false,
                    rowKey: 'infoId',
                    radio: true,
                    tableFormatter: this.titleTableFormatter,
                    params: {
                      customerId: customerObj.customerId
                    }
                  }
                }
              } else if (item.formType == 'receivables') {
                const contractObj = this.getItemRelatveInfo(list, 'contract')
                if (contractObj) {
                  temp.props = {
                    params: {
                      searchList: [
                        { formType: 'text', name: 'contract_id', type: 1, values: [contractObj.contractId] }
                      ]
                    }
                  }
                }

                if (this.action.type == 'update') {
                  item.value ? item.value[0].number = item.value[0].receivablesNum : []
                }
                fieldForm.receivablesNum = item.value ? item.value[0].receivablesNum : ''
              }
            }

            // 特殊字段允许多选
            this.getItemRadio(item, temp)

            // 获取默认值
            if (temp.show) {
              if (this.ignoreFields.includes(temp.field)) {
                fieldForm[temp.field] = this.isEdit ? temp.value : temp.defaultValue
              } else {
                fieldForm[temp.field] = this.getItemValue(item, this.action.data, this.action.type)
              }
            }
            fields.push(temp)
            baseFields.push(item)
          })
          fieldList.push(fields)
        })

        // 处理相关新建金额值的填充
        // if (this.action.type == 'relative') {
        //   const contractItem = this.getItemRelatveInfo(list, 'contract')
        //   // 关联新建填充金额
        //   if (contractItem) {
        //     fieldForm.contractMoney = contractItem ? contractItem.money : ''
        //     fieldForm.invoiceMoney = contractItem ? contractItem.money : ''
        //   }
        // }

        this.baseFields = baseFields
        this.fieldList = fieldList

        const result = this.getFormContentByOptionsChange(fieldList, fieldForm)
        this.fieldForm = result.fieldForm
        this.fieldRules = result.fieldRules

        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    getOtherField() {
      this.otherFields = [
        {
          name: this.$t('crm.invoice.0384f3ad369c60ba25378d3405f748c4'),
          field: 'titleType',
          formType: 'select',
          setting: [{
            name: this.$t('crm.invoice.a07634e445ba64df0e96b8ada613ab40'),
            value: 1
          }, {
            name: this.$t('crm.invoice.d0abeff31cb29bc09affd1b44410eaa9'),
            value: 2
          }]
        }, {
          name: this.$t('crm.invoice.7e4aafcbf5caaee37ea455836661c984'),
          field: 'invoiceTitle',
          formType: 'text',
          setting: []
        },
        {
          name: this.$t('crm.invoice.cfd622fb0f4a4566421824edae400c1c'),
          field: 'taxNumber',
          formType: 'text',
          hidden: false,
          setting: []
        },
        {
          name: this.$t('crm.invoice.38dec60f136704764f02ce366a9105c0'),
          field: 'depositBank',
          formType: 'text',
          hidden: false,
          setting: []
        }, {
          name: this.$t('crm.invoice.fcc5f5150afb93b1b1d99eee892f73ef'),
          field: 'depositAccount',
          formType: 'text',
          hidden: false,
          setting: []
        }, {
          name: this.$t('crm.invoice.401704daaf4f165c95d6b2229dbfa926'),
          field: 'depositAddress',
          formType: 'text',
          hidden: false,
          setting: []
        }, {
          name: this.$t('crm.invoice.174d43f3863df926fbde281f06284de2'),
          field: 'telephone',
          formType: 'text',
          setting: []
        }]

      this.mailFields = [{
        name: this.$t('crm.invoice.1bb4de08c5fd52e25e8ccc7546189b9d'),
        field: 'contactsName',
        formType: 'text',
        setting: []
      },
      {
        name: this.$t('crm.invoice.94bc57d14a3e143f4572ca9c4c2365db'),
        field: 'contactsMobile',
        formType: 'text',
        setting: []
      },
      {
        name: this.$t('crm.invoice.34c35008da552bd95e52244fc87b2c77'),
        field: 'contactsAddress',
        formType: 'position',
        setting: []
      }]
    },

    titleSelectChange(data) {
      const dataValue = data.data
      if (dataValue && dataValue.length) {
        const titleData = dataValue[0]
        for (let index = 0; index < this.otherFields.length; index++) {
          const element = this.otherFields[index]
          this.$set(this.otherFrom, element.field, titleData[element.field])
        }

        const hidden = titleData.titleType == 2
        this.otherFields[2].hidden = hidden
        this.otherFields[3].hidden = hidden
        this.otherFields[4].hidden = hidden
        this.otherFields[5].hidden = hidden
      }
    },

    // fieldValueChange(data) {
    //   const item = this.baseFields[data.index]
    //   const dataValue = data.value
    //   this.$set(this.fieldForm, item.field, dataValue)

    //   if (item.formType == 'customer') {
    //     const contractItem = this.baseFields[data.index + 1]
    //     if (dataValue.length) {
    //       contractItem.disabled = false
    //       const customerItem = dataValue[0]
    //       customerItem['moduleType'] = 'customer'
    //       customerItem['params'] = { checkStatus: [1, 10] }
    //       contractItem['relation'] = customerItem

    //       this.$set(this.mailFrom, 'contactsName', customerItem.contactsName)
    //       this.$set(this.mailFrom, 'contactsMobile', customerItem.contactsMobile)
    //       this.$set(this.mailFrom, 'contactsAddress', customerItem.contactsAddress)

    //       this.titleAction = {
    //         type: 'default',
    //         request: crmCustomerInvoiceInfoAPI,
    //         showScene: false,
    //         showSearch: false,
    //         showCreate: false,
    //         canShowDetail: true,
    //         params: {
    //           customerId: customerItem.customerId
    //         }
    //       }
    //     } else {
    //       contractItem.disabled = true
    //       contractItem['relation'] = {}
    //       // 重置发票信息
    //       this.otherFields.forEach(item => {
    //         if (item.field !== 'titleType') {
    //           this.otherFrom[item.field] = ''
    //         }
    //       })
    //     }

    //     this.$set(this.fieldForm, 'contractId', [])
    //     this.$set(this.fieldForm, 'invoiceMoney', '')
    //     this.$set(this.fieldForm, 'contractMoney', '')
    //     this.$refs.crmForm.validateField(item.field)
    //     this.debouncedGetWkFlowList('invoiceMoney', this.fieldForm)
    //   } else if (item.formType == 'contract') {
    //     const contractValue = dataValue && dataValue.length ? dataValue[0] : null
    //     this.$set(this.fieldForm, 'contractMoney', contractValue ? contractValue.money : '')
    //     this.$set(this.fieldForm, 'invoiceMoney', contractValue ? contractValue.money : '')
    //     this.$refs.crmForm.validateField(item.field)
    //     this.debouncedGetWkFlowList('invoiceMoney', this.fieldForm)
    //   } else {
    //     // 审批流逻辑
    //     this.debouncedGetWkFlowList(item.field, this.fieldForm)
    //   }
    // },

    otherFieldValueChange(data) {
      if (data.field == 'titleType') {
        const hidden = this.otherFrom.titleType == 2
        this.otherFields[2].hidden = hidden
        this.otherFields[3].hidden = hidden
        this.otherFields[4].hidden = hidden
        this.otherFields[5].hidden = hidden
      }
    },

    close() {
      this.$emit('close')
    },

    saveClick() {
      this.loading = true
      const crmForm = this.$refs.crmForm
      crmForm.validate(valid => {
        if (valid) {
          // 如果 afNewApply 说明没有开始审批流
          const wkFlowResult = this.$refs.afNewApply ? this.$refs.afNewApply.getParams() : {
            pass: true,
            flowParams: { list: [] }
          }

          if (wkFlowResult.pass) {
            const params = this.getSubmiteParams(this.baseFields, this.fieldForm)

            // 审批流
            const dataMap = this.getWkFlowDataMap(this.fieldForm, wkFlowResult.flowParams.paramsData?.userFieldNames)
            params.examineFlowData = {
              label: this.examineAdvancedSetting.label,
              dataMap,
              flowDataList: wkFlowResult.flowParams.list
            }

            const entityParams = params.entity // 系统字段
            for (let index = 0; index < this.otherFields.length; index++) {
              const element = this.otherFields[index]
              if (!element.disabled) {
                entityParams[element.field] = this.otherFrom[element.field]
              }
            }

            for (let index = 0; index < this.mailFields.length; index++) {
              const element = this.mailFields[index]
              if (!element.disabled) {
                entityParams[element.field] = this.mailFrom[element.field]
              }
            }

            if (this.isEdit) {
              entityParams.invoiceId = this.action.id
              entityParams.batchId = this.action.batchId
            }

            entityParams.receivablesNum = this.fieldForm.receivablesNum

            crmInvoiceSaveAPI(params)
              .then(res => {
                this.loading = false
                this.close()
                // 回到保存成功
                this.$emit('save-success')
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            this.loading = false
            this.$message.error(this.$t('crm.invoice.3baade356972bb8a23cdb0edf7bbbe84'))
          }
        } else {
          this.loading = false
          // 提示第一个error
          this.getFormErrorMessage(crmForm)
          return false
        }
      })
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action)
    },

    /**
     * change
     */
    formChange(field, index, value, valueList) {
      // 审批流逻辑
      // this.debouncedGetWkFlowList(field.field, this.fieldForm)

      if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
          field.remark === 'options_type' &&
          field.optionsData) {
        const { fieldForm, fieldRules } = this.getFormContentByOptionsChange(this.fieldList, this.fieldForm)
        this.fieldForm = fieldForm
        this.fieldRules = fieldRules
      }
    },

    /**
     * 地址change
     */
    otherChange(data, field) {
      if (field.formType === 'customer') {
        this.itemsForEach(this.fieldList, fieldItem => {
          if (fieldItem.formType === 'contract') {
            // 如果是合同 改变合同样式和传入客户ID
            if (data.value.length > 0) {
              fieldItem.disabled = false
              const customerItem = data.value[0]
              fieldItem.props = {
                params: {
                  searchList: [
                    { formType: 'text', name: 'customer_id', type: 1, values: [customerItem.customerId] },
                    { formType: 'checkStatus', name: 'checkStatus', type: 1, values: [1, 10] }
                  ]
                }
              }

              this.$set(this.mailFrom, 'contactsName', customerItem.contactsName)
              this.$set(this.mailFrom, 'contactsMobile', customerItem.contactsMobile)
              this.$set(this.mailFrom, 'contactsAddress', customerItem.contactsAddress)

              this.titleAction = {
                type: 'invoiceTitle',
                name: this.$t('crm.invoice.ece28d0b350daedfcdcbc2c7503276eb'),
                isCommon: true, // 是统一效果
                fieldList: this.titleFieldList,
                request: crmCustomerInvoiceInfoAPI,
                showHeader: false,
                rowKey: 'infoId',
                radio: true,
                tableFormatter: this.titleTableFormatter,
                params: {
                  customerId: customerItem.customerId
                }
              }
            } else {
              fieldItem.disabled = true
              fieldItem.props = null
              // 重置发票信息
              this.otherFields.forEach(item => {
                if (item.field !== 'titleType') {
                  this.otherFrom[item.field] = ''
                }
              })
            }
            this.fieldForm[fieldItem.field] = []
          }
        })

        // this.$set(this.fieldForm, 'contractId', [])
        this.$set(this.fieldForm, 'invoiceMoney', '')
        this.$set(this.fieldForm, 'contractMoney', '')
        // this.debouncedGetWkFlowList('invoiceMoney', this.fieldForm)

        // 更新下权限 避免 disabled 造成的影响 fieldRules的影响
        const { fieldRules } = this.getFormContentByOptionsChange(this.fieldList, this.fieldForm)
        this.fieldRules = fieldRules
      } else if (field.formType === 'contract') {
        this.itemsForEach(this.fieldList, fieldItem => {
          if (fieldItem.formType === 'receivables') {
            // 如果是合同 改变合同样式和传入合同ID
            if (data.value.length > 0) {
              fieldItem.disabled = false
              fieldItem.props = {
                params: {
                  searchList: [
                    { formType: 'text', name: 'contract_id', type: 1, values: [data.value[0].contractId] }
                  ]
                }
              }
            } else {
              fieldItem.disabled = true
              fieldItem.props = {}
            }
            this.fieldForm[fieldItem.field] = []
            this.$set(this.fieldForm, 'receivablesNum', '')
          }
        })

        const contractValue = data.value && data.value.length ? data.value[0] : null
        this.$set(this.fieldForm, 'contractMoney', contractValue ? contractValue.money : '')
        this.$set(this.fieldForm, 'invoiceMoney', contractValue ? contractValue.money : '')
        // this.debouncedGetWkFlowList('invoiceMoney', this.fieldForm)
      } else if (field.formType === 'receivables') {
        const receivablesValue = data.value && data.value.length ? data.value[0] : []
        this.$set(this.fieldForm, 'receivablesId', receivablesValue)
        this.$set(this.fieldForm, 'receivablesNum', receivablesValue.number)
      }
      this.$set(this.fieldForm, field.field, data.value)
      this.$refs.crmForm.validateField(field.field)
    },

    /**
     * 抬头表格
     */
    titleTableFormatter(row, column, cellValue) {
      if (column.property == 'titleType') {
        return {
          1: this.$t('crm.invoice.c05509d904b8756d6ccd43f5d985dda6'),
          2: this.$t('crm.invoice.9168cee1b6a8faf710bf4818760da4c4')
        }[row[column.property]]
      }
      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    }
  }
}
</script>

<style lang="scss" scoped>
.xh-product {
  padding: 0 15px;
}

// 审核信息 里的审核类型
.examine-type {
  height: 16px;
  padding: 0 8px;
  margin-left: 5px;
  font-size: 12px;
  line-height: 16px;
  color: white;
  background-color: #fd715a;
  border-radius: 8px;
  transform: scale(0.8, 0.8);
}
</style>
